var fs = require('fs');
// var cors = require("cors");
var express = require('express');
var app = express();
// var bodyParser = require('body-parser');
//引用bodyParser 这个不要忘了写
// app.use(bodyParser.json()); // for parsing application/json
// app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

// app.use(cors({credentials: true, origin: 'http://192.168.1.191:8082'}));
//设置跨域访问
app.all('*', function(req, res, next) {  
    res.header('Access-Control-Allow-Origin','*');
    res.header('Access-Control-Allow-Credentials', true); 
    res.header("Access-Control-Allow-Headers", "X-Requested-With");  
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");  
    res.header("X-Powered-By",' 3.2.1')  
    res.header("Content-Type", "application/json;charset=utf-8");  
    next();  
}); 

var path = require('path');
var ejs = require( 'ejs' );

 
//指定静态资源访问目录
app.use(express.static(path.join(__dirname, 'public')));
// app.use(express.static(require('path').join(__dirname, 'views'))); 如果有文件夹存放资源，出现报错的话，那就多use几次就可以了
// 设定views变量，意为视图存放的目录
app.set('views', (__dirname + "/public"));
// app.set('views', __dirname);
// 修改模板文件的后缀名为html
app.set( 'view engine', 'html' );
// 运行ejs模块
app.engine( '.html', ejs.__express );
 
app.get("/", function(req, res) {
  res.render('index');
});


var bitmap1 = null;

//接口123
//响应接口
app.post('/result',function(req,res){
//数据
    let result={
        code:0,
        msg:'分割成功',
        data: '/result.jpg'
    }
    res.send(result)
})


app.post('/test',function(req,res){
    console.log(req.stack);
    console.log(req.body);
    console.log(req.url);
    console.log(req.query);
    res.json(req.body)
})

//开启服务器
var server = app.listen(8082,"192.168.1.191", function () {
        var host = server.address().address;
        var port = server.address().port;
        console.log("App listening at http://%s:%s", host, port)
    })

var AipBodyAnalysisClient = require("baidu-aip-sdk").bodyanalysis;

// 设置APPID/AK/SK
var APP_ID = "18519014";
var API_KEY = "dP6l48zws9zhfuO3R4taiAAE";
var SECRET_KEY = "FFmBeNHAwQOjbScy0Xbpax3CSYVfDFPP";

// 新建一个对象，建议只保存一个对象调用服务接口
var client = new AipBodyAnalysisClient(APP_ID, API_KEY, SECRET_KEY);
var image = fs.readFileSync("zjz.jpg").toString("base64");

// console.log(image)

// 如果有可选参数
var options = {};
options["type"] = "foreground";  //请求人像前景抠图，透明背景

// 带参数调用人像分割

if (image) {
    client.bodySeg(image, options).then(function(result) {
        // var base64Data = imgData.replace(/^data:image\/\w+;base64,/, "");
        bitmap1 = Buffer.from(result.foreground, 'base64');
        // console.log(result.foreground)
         //bitmap1 = result.foreground;
        fs.writeFileSync('./public/result.jpg',bitmap1);    //保存下来的图片 123.jpg
        console.log('分割成功，success!');
    }).catch(function(err) {
        // 如果发生网络错误
        console.log(err);
    });;
}else {
    console.log("等待")
}


